<template>
  <el-dialog
    :title="dataForm.brandId ===0? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    @close="dialogClose">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
             label-width="80px">
      <el-form-item label="品牌名" prop="name">
        <el-input v-model="dataForm.name" placeholder="品牌名"></el-input>
      </el-form-item>
      <el-form-item label="品牌logo地址" prop="logo">

<!--        删除和更新都使用update-file 事件，而不是@delete-logo="deleteLogoAndDb($event)"
-->
        <upload-single-file @update-file="updateLogo($event)" ref="uploadSingleFileRef"

                            :fileUrl="dataForm.brandId === 0?null:dataForm.logo"></upload-single-file>

        <!--      <el-input v-model="dataForm.logo" placeholder="品牌logo地址"></el-input>-->
      </el-form-item>

      <el-form-item label="介绍" prop="descript">
        <el-input v-model="dataForm.descript" placeholder="介绍"></el-input>
      </el-form-item>

      <el-form-item label="显示状态" prop="showStatus">
        <!--      显示状态[0-不显示；1-显示]-->
        <el-select v-model="dataForm.showStatus" placeholder="显示状态">
          <el-option
            :key="1"
            label="显示"
            :value="1">
          </el-option>
          <el-option
            :key="0"
            label="隐藏"
            :value="0">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="检索首字母" prop="firstLetter">
        <el-input v-model="dataForm.firstLetter" placeholder="检索首字母"></el-input>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model="dataForm.sort" placeholder="排序"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>

import uploadSingleFile from '../../../components/upload/uploadSingleFile'
import uploadToAiliOss from '../../../api/uploadToAiliOss'

export default {
  data () {
    /**
     * 自定义表单验证器
     * */
    var sortValidator = (rule, value, callback) => {
      if (value == '') {
        callback(new Error('请输入排序'))
      }
      if (!/^[0-9]*$/.test(value)) {
        callback(new Error('序号必须是一个整数'))
      }

      if (value < 0) {
        callback(new Error('序号必须大于0'))
      }

      // 调用callback() 不传入错误信息代表成功
      callback()
    }
    return {
      visible: false,
      dataForm: {
        brandId: 0,
        name: '',
        logo: '',
        descript: '',
        showStatus: '',
        firstLetter: '',
        sort: 0
      },
      dataRule: {
        name: [
          {required: true, message: '品牌名不能为空', trigger: 'blur'}
        ],
        logo: [
          {required: true, message: '品牌logo地址不能为空', trigger: 'blur'}
        ],
        descript: [
          {required: true, message: '介绍不能为空', trigger: 'blur'}
        ],
        showStatus: [
          {required: true, message: '显示状态[0-不显示；1-显示]不能为空', trigger: 'change'}
        ],
        firstLetter: [
          {
            validator: (rule, value, callback) => {
              if (value == '') {
                callback(new Error('请输入首字母'))
              }
              if (!/^[a-zA-Z]/.test(value)) {
                callback(new Error('请输入字母(a-z或者A-Z之间)'))
              }
              // 调用callback() 不传入错误信息代表成功
              callback()
            },
            trigger: 'blur'
          }
        ],
        sort: [
          {validator: sortValidator, trigger: 'change'}
        ]
      }
    }
  },

  components: {
    uploadSingleFile
  },
  methods: {
    init (id) {
      //this.$refs.single.clearFileNameAndPath();
      /*      this.dataForm = {
              brandId: 0,
              name: '',
              logo: '',
              descript: '',
              showStatus: '',
              firstLetter: '',
              sort: ''
            }*/

      this.dataForm.brandId = id || 0
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.brandId) {
          this.$http({
            url: this.$http.adornUrl(`/pms/brand/info/${this.dataForm.brandId}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.dataForm.name = data.brand.name
              this.dataForm.logo = data.brand.logo
              this.dataForm.descript = data.brand.descript
              this.dataForm.showStatus = data.brand.showStatus
              this.dataForm.firstLetter = data.brand.firstLetter
              this.dataForm.sort = data.brand.sort

              console.log('添加或更新，查询到的品牌是', this.dataForm)
            }
          })
        }
      })
    },
    // 表单提交
    dataFormSubmit () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/pms/brand/${!this.dataForm.brandId ? 'save' : 'update'}`),
            method: 'post',
            data: this.$http.adornData({
              'brandId': this.dataForm.brandId || undefined,
              'name': this.dataForm.name,
              'logo': this.dataForm.logo,
              'descript': this.dataForm.descript,
              'showStatus': this.dataForm.showStatus,
              'firstLetter': this.dataForm.firstLetter,
              'sort': this.dataForm.sort
            })
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    },
    updateLogo (val) {
      console.log('父组件中的logo更新了', val)
      this.dataForm.logo = val
    },
    deleteLogoAndDb (logoKey) {

      uploadToAiliOss.deleteFileOfDbAndOss(this.dataForm.brandId, logoKey).then(({data}) => {

        this.$message({
          message: `${this.dataForm.name}的logo删除成功`,
          type: 'success'
        })
        this.dataForm.logo = "";

      })

    },
    dialogClose () {
      /*this.dataForm = {
        brandId: 0,
        name: '',
        logo: '',
        descript: '',
        showStatus: '',
        firstLetter: '',
        sort: 0
      }*/
      this.$refs.uploadSingleFileRef.fileList = [];
      // clearTimeout(this.$refs.uploadSingleFileRef.updatePolicyTimer);

    }
  },
  watch: {}
}
</script>
